package com.weixin.cp.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.weixin.cp.config.WxCpConfiguration;

import ops.weixin.cp.api.WxCpService;
import ops.weixin.cp.util.StringUtils;
import ops.weixin.cp.util.crypto.WxCpCryptUtil;

/**
 * 企业微信认证入口
 * 
 * @author SuM
 * @date: 2019年12月23日下午5:29:08
 */
@RestController
@RequestMapping("/wx/cp/portal")
public class WxPortalController {
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	  *  接收消息服务器配置认证
	 */
	@GetMapping(produces = "text/plain;charset=utf-8")
	public String authGet(@RequestParam(name = "msg_signature", required = false) String signature,
			@RequestParam(name = "timestamp", required = false) String timestamp,
			@RequestParam(name = "nonce", required = false) String nonce,
			@RequestParam(name = "echostr", required = false) String echostr) {
		this.logger.info("\n接收到来自微信服务器的认证消息：signature = [{}], timestamp = [{}], nonce = [{}], echostr = [{}]",
				signature, timestamp, nonce, echostr);

		if (StringUtils.isAnyBlank(signature, timestamp, nonce, echostr)) {
			throw new IllegalArgumentException("请求参数非法，请核实!");
		}

		final WxCpService wxCpService = WxCpConfiguration.getCpService();

		if (wxCpService.checkSignature(signature, timestamp, nonce, echostr)) {
			return new WxCpCryptUtil(wxCpService.getWxCpConfigStorage()).decrypt(echostr);
		}

		return "非法请求";
	}

	/**
	  * 微信消息接收入口
	 */
	@PostMapping(produces = "application/xml; charset=UTF-8")
	public String post(@RequestBody String requestBody, @RequestParam("msg_signature") String signature,
			@RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce) {
		this.logger.info("\n接收微信消息体：[signature=[{}], timestamp=[{}], nonce=[{}], requestBody=[\n{}\n] ", signature,
				timestamp, nonce, requestBody);

		return "";
	}
}
